package org.deri.socializer;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;

import org.deri.socializer.com.http.HTTPClient;
import org.deri.socializer.com.http.Website;
import org.deri.socializer.com.xmpp.XmppClient;
import org.deri.socializer.com.xmpp.XmppGroupChat;
import org.deri.socializer.com.xmpp.XmppUser;
import org.jivesoftware.smack.packet.Message;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings.Secure;

public class SocializerApplication extends Application {
	
	// lat: 53.290128
	// lng: -9.073945
	
	//public static final String DEFAULT_HTTP_HOST = "109.255.155.209";
	public static final String DEFAULT_HTTP_HOST = "vmusm02.deri.ie";
	public static final String DEFAULT_XMPP_HOST = "vmusm02.deri.ie";
	public static final String DEFAULT_RESOURCE = "conference";
	public static final String XMPP_GROUP_CHAT_SUFFIX_WEB = ".web";
	public static final String XMPP_GROUP_CHAT_SUFFIX_GEO = ".geo";
	private LocationManager locationManager;
	private LocationListener locationListener;
	
	
	int userId								= 0;
	XmppClient xmppClient					= null;
	HTTPClient httpClient					= null;
	String currentDomainWeb = "deri.ie";
	String currentDomainGeo = "---dummy---";

	public boolean hasXmppConnection = false;
	public Message lastMessage = null;
	
	public static byte runningActivities = 0;
	
	
    /** Called when the activity is first created. */
    public void onCreate() {
        
    	SharedPreferences preferences = getSharedPreferences("myCustomSharedPrefs", Activity.MODE_PRIVATE);
    	
    	String xmppHost = preferences.getString("xmpp_host", DEFAULT_XMPP_HOST);
    	String xmppResource = preferences.getString("xmpp_resource", DEFAULT_RESOURCE);
    	String xmppUsername = preferences.getString("xmpp_username", "homer");
    	String xmppPassword = preferences.getString("xmpp_password", "pwd");

    	
        //XMPPUser xmppUser = new XMPPUser(SocializerApplication.DEFAULT_XMPP_HOST, DEFAULT_RESOURCE, "homer", "pwd");
    	

    	this.xmppClient = new XmppClient(this);
        this.httpClient = new HTTPClient();

    	this.hasXmppConnection = this.xmppConnect(xmppHost, xmppResource, xmppUsername, xmppPassword, false);

        initLocationManager();
    }
 


	public boolean xmppConnect(String host, String resource, String username, String password, boolean doRegister) {
    	if (this.xmppClient.isConnected())
    		this.xmppClient.disconnect();
    	XmppUser xmppUser = new XmppUser(host, resource, username, password);
    	
    	boolean success = this.xmppClient.login(xmppUser, doRegister);
    	this.userId = -1;
    	if (success) {
    		//this.userId = this.httpClient.getUserId("http://" + SocializerApplication.DEFAULT_HTTP_HOST + "/weblocator/do_command.php", username);
    		this.userId = this.httpClient.addNewUser("http://" + SocializerApplication.DEFAULT_HTTP_HOST + "/weblocator/do_command.php", username, password, host, resource);
    	}
    		
    	
        return success;
    }

    public XmppClient getXMPPClient() {
    	return this.xmppClient;
    }

    public HTTPClient getHTTPClient() {
    	return this.httpClient;
    }
    
	public String getCurrentDomainWeb() {
		return currentDomainWeb;
	}


	public void setCurrentDomainWeb(String currentDomainWeb) {
		this.currentDomainWeb = currentDomainWeb;
	}

	public String getCurrentDomainGeo() {
		return currentDomainGeo;
	}


	public void setCurrentDomainGeo(String currentDomainGeo) {
		this.currentDomainGeo = currentDomainGeo;
	}
	
	/**
	 * Initialise the location manager.
	 */
	private void initLocationManager() {
		
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		
		
		
		locationListener = new LocationListener() {
 
			public void onLocationChanged(Location newLocation) {
				
				joinGeoGroupChat(newLocation);
//				sendGeoData(newLocation);
			}
 
			public void onProviderDisabled(String arg0) {
			}
 
			public void onProviderEnabled(String arg0) {
			}
 
			public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
			}
		};
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 0, locationListener);
 
	}
	
	
	private void sendGeoData(Location location){
		System.out.println("PUSH");
		String url = "http://lsm.deri.ie/volvorace/oceanrace?api=update&" +
				"userId=" + Secure.getString(getBaseContext().getContentResolver(), Secure.ANDROID_ID) + 
				"&lat=" + Double.toString(location.getLatitude()) + 
				"&long=" + Double.toString(location.getLongitude());
		
		try {
			URL Url	=	new URL(url);
			Url.openConnection();
			Url.openStream();
		
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		}
	}
	
	private void joinGeoGroupChat(Location location) {

		this.httpClient.updateLocationGeo("http://" + SocializerApplication.DEFAULT_HTTP_HOST + "/weblocator/do_command.php", this.userId, location.getLatitude(), location.getLongitude());
		
		ArrayList<Website> locations = this.httpClient.getClosestWebsiteGeo("http://" + SocializerApplication.DEFAULT_HTTP_HOST + "/weblocator/do_command.php", location, 100, 1);
		
		Iterator<Website> locIter = locations.iterator();
		Website loc = null;
		while (locIter.hasNext())
			loc = locIter.next();

		XmppGroupChat geoGroupChat = this.xmppClient.getCurrentGeoGroupChat();
		if (loc != null) {
			
			if (geoGroupChat == null) {
				XmppGroupChat groupChat = this.xmppClient.createGeoGroupChat(loc.getVLoc());
				groupChat.join();
				this.xmppClient.setLastXmppGeoChat(groupChat);
			} else {
				if (geoGroupChat.getRoomName().equals((loc.getVLoc() + ".geo"))) {
					return;
				}
				this.xmppClient.leaveGroupChat(this.xmppClient.getCurrentGeoGroupChat().getRoomName());
				XmppGroupChat groupChat = this.xmppClient.createGeoGroupChat(loc.getVLoc());
				groupChat.join();
				this.xmppClient.setLastXmppGeoChat(groupChat);
				//this.xmppClient.joinGeoGroupChat(loc.getDomain());
			}

		} else {
		
			if (geoGroupChat != null) {
		
				this.xmppClient.leaveGroupChat(geoGroupChat.getRoomName());
			} else {
				
			}
		}
	}

	
	public void checkActivityState() {
		
		if (SocializerApplication.runningActivities == 0) {
			this.pauseApplication();
		}
	}
	
	public void pauseApplication() {
		
		
		// Leave all group chats
		this.xmppClient.leaveAllGroupChats();
		
		// Remove user location
		this.httpClient.updateLocationGeo("http://" + SocializerApplication.DEFAULT_HTTP_HOST + "/weblocator/do_command.php", this.userId, 0.0, 0.0);
		
	}
	

}

